package com.gitee.hifong45.config;

import com.gitee.hifong45.Str;
import com.gitee.hifong45.extknife.SwaggerProperties;
import com.github.xiaoymin.knife4j.spring.configuration.Knife4jProperties;
import com.github.xiaoymin.knife4j.spring.configuration.Knife4jSetting;
import com.github.xiaoymin.knife4j.spring.extension.Knife4jOpenApiCustomizer;
import com.github.xiaoymin.knife4j.spring.filter.SecurityBasicAuthFilter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Slf4j
@Configuration
@EnableConfigurationProperties({Knife4jProperties.class, SwaggerProperties.class})
// @EnableSwagger2WebMvc
public class ExtKnifeConfig {
    @Autowired
    private Environment environment;

    @Bean
    @ConditionalOnMissingBean
    public Knife4jOpenApiCustomizer knife4jOpenApiCustomizer(Knife4jProperties knife4jProperties) {
        log.debug("############ Ext Knife 自定义初始化 ############");

        knife4jProperties.setEnable(true); // 允许增强模式
        Knife4jSetting setting = knife4jProperties.getSetting();
        if (setting == null){
            setting = new Knife4jSetting();
        }

        setting.setEnableVersion(true); // 后台接口有变化，前端显示蓝色小点
        setting.setEnableReloadCacheParameter(true); // “刷新变量”按钮
        setting.setEnableFilterMultipartApis(true); // 过滤多个
        setting.setEnableFooter(false); // 不允许Footer
        setting.setEnableFooterCustom(true); // 允许自定义Footer
        setting.setFooterCustomContent("Apache License 2.0 | Copyright DevDeng");

        // 修改参数配置
        knife4jProperties.setSetting(setting);

        return new Knife4jOpenApiCustomizer(knife4jProperties);
    }

    @Bean
    @ConditionalOnMissingBean(SecurityBasicAuthFilter.class)
    public SecurityBasicAuthFilter securityBasicAuthFilter(Knife4jProperties knife4jProperties) {
        boolean enableAuth = true;
        String userName = "dev", userPass = "00071011";

        if(environment != null) {
            userName = Str.orElse(environment.getProperty("devdeng.auth.username"), userName);
            userPass = Str.orElse(environment.getProperty("devdeng.auth.usercode"), userPass);
        }

        return new SecurityBasicAuthFilter(enableAuth, userName, userPass);
    }

}